package com.martini.satoken01.service;

import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Redis缓存服务Service
 *
 * @author martini at 2021/12/17 23:42
 */
public class RedisLimitInfoCacheServiceImpl implements LimitInfoCacheService {

    // 注意如果使用Service注入容器，将会替代原先map保存方案

    private RedisTemplate<String, Object> redisTemplate;

    public RedisLimitInfoCacheServiceImpl(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public String info() {
        return "redisCacheInfoService";
    }

    @Override
    public void put(Object key, Object value) {
        this.redisTemplate.opsForValue().set(key.toString(), value);
    }

    @Override
    public void put(Object key, Object value, long timeout, TimeUnit timeUnit) {
        this.redisTemplate.opsForValue().set(key.toString(), value, timeout, timeUnit);
    }

    @Override
    public Object get(Object key) {
        return this.redisTemplate.opsForValue().get(key);
    }

    @Override
    @SuppressWarnings({"unchecked"})
    public <T> T get(Object key, Class<T> classType) {
        return (T) this.redisTemplate.opsForValue().get(key);
    }

    @Override
    public Long listLeftPush(String key, Object value) {
        return this.redisTemplate.opsForList().leftPush(key, value);
    }

    @Override
    public List<Object> listRange(String key, long start, long end) {
        return this.redisTemplate.opsForList().range(key, start, end);
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> List<T> listRange(String key, long start, long end, Class<T> classType) {
        List<Object> range = this.redisTemplate.opsForList().range(key, start, end);
        if (range == null) {
            return null;
        }
        return range.stream().map(obj -> (T) obj).collect(Collectors.toList());
    }

    @Override
    @SuppressWarnings({"unchecked"})
    public <T> T listIndex(String key, long index, Class<T> classType) {
        return (T) this.redisTemplate.opsForList().index(key, index);
    }

    @Override
    public Long listRemove(String key, long count, Object obj) {
        return this.redisTemplate.opsForList().remove(key, count, obj);
    }

}
